package cn.rkylin.oms.push.adapter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.Rop.api.DefaultRopClient;
import com.Rop.api.request.XvpOrderDeliverRequest;
import com.Rop.api.request.XvpSkuUpdatestockRequest;
import com.Rop.api.response.XvpOrderDeliverResponse;
import com.Rop.api.response.XvpSkuUpdatestockResponse;
import com.alibaba.fastjson.JSON;

import cn.rkylin.core.IDataBaseFactory;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.common.dto.DBLog;
import cn.rkylin.oms.common.utils.LogUtil;
import cn.rkylin.oms.ectrade.dao.IEcOrderDAO;
import cn.rkylin.oms.ectrade.vo.EcOrderVO;
import cn.rkylin.oms.system.logistics.dao.ILogisticsDAO;
import cn.rkylin.oms.system.logistics.vo.LogisticsVO;
import cn.rkylin.oms.system.shop.domain.Shop;

/**
 * XvpPushVisitor
 * 
 * @author qitao
 *
 */
@Service("xvpPushVisitor")
public class XvpPushVisitor extends PushVisitor {

	// 数据库访问对象
	@Autowired
	private IDataBaseFactory dao;

	@Autowired
	private IEcOrderDAO ecOrderDAO;

	@Autowired
	private ILogisticsDAO ilgstDAO;

	@Autowired
	private LogUtil logUtil;

	private final String sessionKey = "sessionKey";

	/**
	 * 系统发货
	 * 
	 * @param shop
	 *            店铺ID
	 * @param ecItemCode
	 *            平台商品编码
	 * @param ecTradeCode
	 *            平台交易单号
	 * @param ecSkuCode
	 *            平台规格编码
	 * @return
	 */
	public Map<String, Object> pushSystemConsignment(Shop shop, String ecItemCode, String ecTradeCode, String ecSkuCode,
			String shipTime) {
		return null;
	}

	/**
	 * 自己联系物流（线下物流）发货
	 * 
	 * @param shop
	 *            网店对象
	 * @param ecTradeCode
	 *            平台交易编码
	 * @param lgstNo
	 *            物流单号
	 * @param lgstCode
	 *            物流公司编码
	 * @return 结果对象
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> pushTradeOfflineSend(Shop shop, String ecTradeCode, String lgstNo, String lgstCode)
			throws Exception {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		String strError = "";

		// 发货的订单商品id的列表(用逗号分隔)
		Map<String, String> ecOrderMap = new HashMap<String, String>();
		ecOrderMap.put("ecTradeCode", ecTradeCode);
		List<EcOrderVO> listOrderDeal = ecOrderDAO.findOrderList("selectOrderByTradeItemSku", ecOrderMap);
		String orderItemIds = "";
		for (EcOrderVO ecOrderVO : listOrderDeal) {
			orderItemIds = orderItemIds + "," + ecOrderVO.getEcSkuCode();
		}
		orderItemIds = "".equals(orderItemIds) ? "" : orderItemIds.substring(1);

		// 快递公司名称
		LogisticsVO lgstVO = new LogisticsVO();
		CurrentUser currUser = WebContextFactory.getWebContext().getCurrentUser();
		if (currUser == null) {
		    lgstVO.setPrjId(shop.getPrjId());
		} else {
			lgstVO.setPrjId(currUser.getCurrentProject().getPrjId());
		}
		lgstVO.setLgstCode(lgstCode);
		List<LogisticsVO> lgstList = ilgstDAO.getLgstByCondition(lgstVO);
		String lgstName = "";
		if (lgstList.size() > 0) {
			LogisticsVO lgstData = lgstList.get(0);
			lgstName = lgstData.getLgstName();
		}

		// ruixue.xvp.order.deliver
		DefaultRopClient ropClient = new DefaultRopClient(shop.getApiUrl(), shop.getAppKey(), shop.getAppSecret(),
				"json");
		XvpOrderDeliverRequest req = new XvpOrderDeliverRequest();
		req.setOrder_id(ecTradeCode);
		req.setOrder_item_id_list(orderItemIds);
		req.setLogistic_flg(1);
		req.setLogistics_company_code(lgstCode);
		req.setLogistics_company_name(lgstName);
		req.setLogistics_num(lgstNo);
		XvpOrderDeliverResponse rsp = ropClient.execute(req, sessionKey);

		// 记录日志
		logUtil.info(new DBLog(ecTradeCode, "ruixue.xvp.order.deliver", "pushTradeOfflineSend",
				"[" + JSON.toJSONString(req) + "," + rsp.getBody() + "]"));

		if (!rsp.isSuccess()) {
			if (StringUtils.isNotBlank(rsp.getSubMsg())) {
				strError = rsp.getSubMsg();
			} else {
				strError = rsp.getMsg();
			}
			returnMap.put("success", "n");
			returnMap.put("msg", strError);
		} else {
			returnMap.put("success", "y");
			returnMap.put("msg", "");
		}

		return returnMap;
	}

	/**
	 * 商品上架
	 * 
	 * @param shop
	 *            网店对象
	 * @param ecItemCode
	 *            平台商品编码
	 * @param stockCount
	 *            库存数量
	 * @return 结果对象
	 */
	@Override
	public Map<String, Object> pushItemListing(Shop shop, String ecItemCode, String stockCount) {
		return null;
	}

	/**
	 * 商品下架
	 * 
	 * @param shop
	 *            网店对象
	 * @param ecItemCode
	 *            平台商品编码
	 * @return 结果对象
	 */
	@Override
	public Map<String, Object> pushItemDeListing(Shop shop, String ecItemCode) {
		return null;
	}

	/**
	 * 批量同意退款
	 * 
	 * @param shop
	 *            网店对象
	 * @param ecRefundCodes
	 *            平台退款编号, 按照 ","号分割
	 * @param code
	 *            短信验证码
	 * @return 结果对象
	 */
	@Override
	public Map<String, Object> pushRefundBatchAgree(Shop shop, String ecRefundCodes, String code) {
		return null;
	}

	/**
	 * 拒绝退款
	 * 
	 * @param shop
	 * @param ecRefundCode
	 *            退款单号
	 * @param refuseMessage
	 *            拒绝退款时的说明信息，长度2-200
	 * @param refuseReasonId
	 *            拒绝原因编号，会提供用户拒绝原因列表供选择
	 * @param refusePath
	 *            拒绝退款时的退款凭证对应的本地绝对路径，一般是卖家拒绝退款时使用的发货凭证，最大长度130000字节，支持的图片格式： GIF,
	 *            JPG, PNG支持的文件类型：gif,jpg,png
	 * @return
	 */
	@Override
	public Map<String, Object> pushRefundRefuse(Shop shop, String ecRefundCode, String refuseMessage,
			String refuseReasonId, String refusePath) {
		return null;
	}

	/**
	 * 卖家同意退货
	 * 
	 * @param shop
	 * @param ecRefundCode
	 *            退款单编号
	 * @param name
	 *            卖家姓名，淘宝退款为必填项。
	 * @param address
	 *            卖家提供的退货地址，淘宝退款为必填项。
	 * @param post
	 *            卖家提供的退货地址的邮编，淘宝退款为必填项
	 * @param tel
	 *            卖家座机，淘宝退款为必填项。
	 * @param mobile
	 *            卖家手机，淘宝退款为必填项。
	 * @param remark
	 *            卖家退货留言，天猫退款为必填项。
	 * @param sellerAddressId
	 *            卖家收货地址编号，天猫退款为必填项。
	 * @return
	 */
	@Override
	public Map<String, Object> pushReturnGoodsAgree(Shop shop, String ecRefundCode, String name, String address,
			String post, String tel, String mobile, String remark, String sellerAddressId) {
		return null;
	}

	/**
	 * 审核退款单
	 * 
	 * @param shop
	 *            网店对象
	 * @param ecRefundCode
	 *            平台退款编号
	 * @param erpStatus
	 *            审核状态 已审核/未审核
	 * @return 结果对象
	 */
	@Override
	public Map<String, Object> pushRefundAppr(Shop shop, String ecRefundCode, String erpStatus) {
		return null;
	}

	@Override
	public Map<String, Object> pushItemQuantityUpdate(Shop shop, String ecItemCode, String skuId, String stockCount) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		String strError = "";
		try {
			Integer quantity = Integer.valueOf(stockCount);

			// ruixue.xvp.sku.updatestock 用xml格式有问题所以，用json
			DefaultRopClient client = new DefaultRopClient(shop.getApiUrl(), shop.getAppKey(), shop.getAppSecret(),"json");
			XvpSkuUpdatestockRequest req = new XvpSkuUpdatestockRequest();
			req.setStore_id(Integer.parseInt(shop.getShopAccount()));
			req.setProduct_id(Integer.parseInt(ecItemCode));
			req.setSku_id(Integer.parseInt(skuId));
			req.setStock(quantity);

			XvpSkuUpdatestockResponse rsp = client.execute(req, shop.getSessionKey());

			// 操作错误，返回错误结果
			if (!rsp.isSuccess()) {
				if (StringUtils.isNotBlank(rsp.getSubMsg())) {
					strError = rsp.getSubMsg();
				} else {
					strError = rsp.getMsg();
				}
				returnMap.put("success", "n");
				returnMap.put("msg", strError);
			} else {
				returnMap.put("success", "y");
				returnMap.put("msg", "");
			}

		} catch (Exception e) {
			e.printStackTrace();
			returnMap.put("success", "n");
			returnMap.put("msg", e.getMessage());
		}
		return returnMap;
	}

	@Override
	public Map<String, Object> pushSkuQuantityUpdate(Shop shop, String ecItemCode, String ecSkuCode,
			String stockCount) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		String strError = "";
		try {

			Long numIid = Long.valueOf(ecItemCode);
			Integer skuId = Integer.valueOf(ecSkuCode);
			Integer quantity = Integer.valueOf(stockCount);

			// ruixue.xvp.sku.updatestock
			DefaultRopClient client = new DefaultRopClient(shop.getApiUrl(), shop.getAppKey(), shop.getAppSecret(),"json");
			XvpSkuUpdatestockRequest req = new XvpSkuUpdatestockRequest();

			req.setStore_id(Integer.parseInt(shop.getShopAccount()));
			req.setProduct_id(Integer.parseInt(ecItemCode));
			req.setSku_id(skuId);
			req.setStock(quantity);
			if (quantity > 0) {
				req.setStock(quantity);
			} else {
				req.setStock(0);
			}

			XvpSkuUpdatestockResponse rsp = client.execute(req, shop.getSessionKey());

			// 操作错误，返回错误结果
			if (!rsp.isSuccess()) {
				if (StringUtils.isNotBlank(rsp.getSubMsg())) {
					strError = rsp.getSubMsg();
				} else {
					strError = rsp.getMsg();
				}
				returnMap.put("success", "n");
				returnMap.put("msg", strError);
			} else {
				returnMap.put("success", "y");
				returnMap.put("msg", "");
			}

		} catch (Exception e) {
			e.printStackTrace();
			returnMap.put("success", "n");
			returnMap.put("msg", e.getMessage());
		}
		return returnMap;
	}

	/**
	 * 修改一笔交易备注
	 */
	public Map<String, Object> pushTradeMemo(Shop shop, Long tid, String memo, Long flag) throws Exception {
		Map<String, Object> returnMap = new HashMap<String, Object>();

		return returnMap;
	}

}
